import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    list: [],
    inputValue: 'aaa',
    nextId: 5,
    viewKey: 'all',
  },
  mutations: {
    initlist(state, list) {
      state.list = list
    },
    changeInputValue(state, val) {
      state.inputValue = val
    },
    addHandleLise(state) {
      const obj = {
        id: state.nextId,
        info: state.inputValue,
        done: state.list.done,
      }
      state.list.push(obj)
      state.inputValue = ''
      state.nextId++
    },
    cleanItemById(state, id) {
      const i = state.list.findIndex((x) => {
        x.id === id
      })
      state.list.splice(i, 1)
    },
    cbChangeDone(state, params) {
      const i = state.list.findIndex((x) => x.id === params.id)
      if (i !== -1) {
        state.list[i].done = params.stus
      }
    },
    clean(state) {
      state.list = state.list.filter((x) => {
        return x.done === false
      })
    },
    viewKey(state, key) {
      state.viewKey = key
    },
  },
  actions: {
    getlist(context) {
      axios.get('/list.json').then(({ data }) => {
        context.commit('initlist', data)
      })
    },
  },
  modules: {},
  getters: {
    unDoneLength(state) {
      return state.list.filter((x) => {
        return x.done === false
      }).length
    },
    infoList(state) {
      if (state.viewKey === 'all') {
        return state.list
      }
      if (state.viewKey === 'undone') {
        return state.list.filter((x) => !x.done)
      }
      if (state.viewKey === 'done') {
        return state.list.filter((x) => x.done)
      }
    },
  },
})
